package com.simple.crawler.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternUtils;
import org.springframework.core.type.classreading.CachingMetadataReaderFactory;
import org.springframework.core.type.classreading.MetadataReaderFactory;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;

public class ResourceUtils {

    private static final Logger logger = LoggerFactory.getLogger(ResourceUtils.class);

    public static Set<Class<?>> getClassByPattern(ResourceLoader resourceLoader, String pattern) throws IOException {
        ResourcePatternResolver resolver = ResourcePatternUtils.getResourcePatternResolver(resourceLoader);
        Resource[] resources = resolver.getResources(pattern);
        if (resources == null || resources.length == 0) {
            logger.info("未扫描到class");
            return new HashSet<>();
        }
        return Arrays.asList(resources).stream().map(r -> getClassForPkg(((ClassPathResource) r).getPath())).collect(Collectors.toSet());
    }

    public static Class<?> getClassForPkg(String pkg) {
        try {
            return Class.forName(pkg);
        } catch (Exception e) {
            return null;
        }
    }

}
